package com.tyc.es.service;

import com.alibaba.fastjson.JSONObject;
import com.tyc.es.model.Page;
import com.tyc.es.model.Product;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.MatchAllQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

@Service
public class ProductServiceImpl implements ProductService{
    @Autowired
    @Qualifier("restHighLevelClient")
    private RestHighLevelClient client;

    @Override
    public boolean insert(List<Product> products) throws IOException {
        BulkRequest bulkRequest = new BulkRequest("tm_product");
        for (int i = 0; i < products.size(); i++) {
            String id = String.valueOf(i+1);
            IndexRequest indexRequest = new IndexRequest().source(JSONObject.toJSONString(products.get(i)), XContentType.JSON).id(id);
            bulkRequest.add(indexRequest);
        }
        BulkResponse bulk = client.bulk(bulkRequest, RequestOptions.DEFAULT);
        return !bulk.hasFailures();
    }

    @Override
    public Page<Product> getAll(int size, int num) throws IOException {
        SearchRequest request = new SearchRequest("tm_product");
        SearchResponse response1 = client.search(request, RequestOptions.DEFAULT);

        long value = response1.getHits().getTotalHits().value;
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        MatchAllQueryBuilder matchAllQuery = QueryBuilders.matchAllQuery();
        sourceBuilder.query(matchAllQuery);
        sourceBuilder.from(0);
        sourceBuilder.size(5);
        request.source(sourceBuilder);
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);

        return null;
    }


}
